package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 后台任务插件
 */
public class FunddailyreportTaskPlugin extends AbstractTask implements Plugin {

    private static Log log = LogFactory.getLog(FunddailyreportTaskPlugin.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        try {
            log.info("开始执行【生成资金日报填写情况】调度任务");
            Date bizDate = new Date();

            boolean isHaveParameter = false;
            if(map != null && map.get("bizDate") != null && !"".equals(map.get("bizDate"))){
                bizDate = new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("bizDate"));
                isHaveParameter = true;
            }

            gnerateData(requestContext, bizDate);

            if(!isHaveParameter){
                // 如果调度那边没时间，就取当天和前一天；如果有时间，就直接获取填的那个时间
                // 获取前一天
                // 1. 获取Calendar实例
                Calendar calendar = Calendar.getInstance();
                // 2. 设置Calendar的时间为bizDate
                calendar.setTime(bizDate);
                // 3. 减去1天（DATE字段表示“日”）
                calendar.add(Calendar.DATE, -1);

                // 4. 转换为前一天的Date
                bizDate = calendar.getTime();

                gnerateData(requestContext, bizDate);
            }


        } catch (Exception e) {
            log.error("执行【生成资金日报填写情况】调度任务出错");
            e.printStackTrace();
            throw new KDBizException(e.getMessage());
        }
        log.info("执行【生成资金日报填写情况】调度任务结束");
    }


    private void gnerateData(RequestContext requestContext, Date bizDate){
        LocalDate localDate = LocalDate.from(LocalDateTime.ofInstant(bizDate.toInstant(), ZoneId.systemDefault()).toLocalDate());
        Date startdate = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        LocalDateTime enddateTime = localDate.atTime(23, 59, 59);
        Date enddate = Date.from(enddateTime.atZone(ZoneId.systemDefault()).toInstant());

        QFilter filter = new QFilter("nckd_bizdate", QCP.large_equals, startdate).and("nckd_bizdate", QCP.less_equals, enddate);
        // 获取指定或者当天日期的单据，有则更新，无则创建
        DynamicObject funddailyreport = BusinessDataServiceHelper.loadSingleFromCache("nckd_funddailyreport", filter.toArray());
        if(funddailyreport == null){
            funddailyreport = BusinessDataServiceHelper.newDynamicObject("nckd_funddailyreport");
            CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(funddailyreport.getDataEntityType().getName(), funddailyreport, null);
            String billno = CodeRuleServiceHelper.getNumber(codeRule, funddailyreport);
            // 编码
            funddailyreport.set("billno", billno);
            DynamicObject org = BusinessDataServiceHelper.loadSingleFromCache("bos_org", "id", new QFilter("number", QCP.equals, "0").toArray());
            // 组织 默认0
            funddailyreport.set("org", org.getPkValue());
            funddailyreport.set("billstatus", "C");
        }
        // 已填报数量
        int completed = 0;
        // 未填报数量
        int incomplete = 0;
        // 单位总数
        int orgqty = 0;
        // 业务日期
        funddailyreport.set("nckd_bizdate", bizDate);
        // 资金日报单组织维护单
        QFilter[] funddaybillorgFilter = new QFilter("billstatus", QCP.equals, "C").toArray();
        DynamicObject[] funddaybillorgObj = BusinessDataServiceHelper.load("nckd_funddaybillorg","id",funddaybillorgFilter,"createtime desc");
        if (funddaybillorgObj != null && funddaybillorgObj.length > 0) {
            // 取最新的一条数据
            DynamicObject funddaybillorg = BusinessDataServiceHelper.loadSingle(funddaybillorgObj[0].getPkValue(), "nckd_funddaybillorg");
            DynamicObjectCollection funddaybillorgentitys = funddaybillorg.getDynamicObjectCollection("entryentity");

            DynamicObjectCollection funddailyreportentitys = funddailyreport.getDynamicObjectCollection("entryentity");//获取单据体数据集
            funddailyreportentitys.clear();
            DynamicObject entry = null;
            orgqty = funddaybillorgentitys.size();
            for (DynamicObject entryentity : funddaybillorgentitys) {
                entry = new DynamicObject(funddailyreportentitys.getDynamicObjectType());//获取单据体数据类型
                entry.set("nckd_org", entryentity.getDynamicObject("nckd_org"));

                QFilter[] funddaybillfilter = new QFilter("nckd_bizdate", QCP.large_equals, startdate).
                        and("nckd_bizdate", QCP.less_equals, enddate).
                        and("org.id",QCP.equals, entryentity.getDynamicObject("nckd_org").getPkValue()).toArray();
                DynamicObjectCollection funddaybills = QueryServiceHelper.query("nckd_funddaybill", "billstatus,id,billno", funddaybillfilter, "createtime desc");
                if(funddaybills != null && funddaybills.size() > 0){
                    DynamicObject funddaybill = funddaybills.get(0);
                    String status = funddaybill.getString("billstatus");
                    if("C".equals(status)){
                        completed++;
                    }else{
                        incomplete++;
                    }
                    entry.set("nckd_funddaybillno", funddaybill.getString("billno"));
                    entry.set("nckd_funddaybillid", funddaybill.get("id"));
                    entry.set("nckd_billstatus", status);
                }else{
                    incomplete++;
                }
                funddailyreportentitys.add(entry);
            }
            funddailyreport.set("entryentity", funddailyreportentitys);
        }
        funddailyreport.set("nckd_orgqty", orgqty);
        funddailyreport.set("nckd_completed", completed);
        funddailyreport.set("nckd_incomplete", incomplete);
        funddailyreport.set("creator", requestContext.getCurrUserId());
        OperationResult nckdFunddailyreport = SaveServiceHelper.saveOperate("nckd_funddailyreport", new DynamicObject[]{funddailyreport});
    }

}